var grid;
var form;
var form1;
$(function () {

    //加载该页面前，先判断该模块的权限
    //获取当前登录的用户的权限
    var permission = document.cookie.split(";")[1].split("=")[1];
    var b = String(permission).split('');
    for (var i = 0; i < b.length; i++) {
        console.log(b[i]);
    }
    var moudle51 = b[15];
    //如果模块权限为1，即只能查询此模块下的数据，不能进行修改（禁用和重置密码不能使用）
    //系统管理
    flag = true;
    if (moudle51 == 1) {
        $("#addNewBtn").css('display', 'none');
        flag = false;
    }
    var pageNo = 1;
    var pageSize = 5;
    var grid_selector = "#grid-table";
    var pager_selector = "#grid-pager";

    //初始化数据表格
    grid = $(grid_selector).jqGrid({
        cellEdit: flag,
        datatype: "json",
        url: 'getUserList',
        mtype: 'POST',
        page: pageNo,
        postData: {
            'tel': $("#userAccount").val(),
            'username': $("#userName").val(),
            'rooleid': $("#sUserRole option:selected").val(),
            'bankid': $("#sUserBank option:selected").val(),
            'organization': $("#sUserOrg option:selected").val(),
            'state': $("#userState option:selected").val(),
        },
        height: 380,
        width: 300,
        colNames: ['', '', '使用者账号', '使用者名称', "所属银行", '所属机构', "使用者角色", "状态"],
        colModel: [
            {
                name: 'astate',
                index: 'astate',
                width: 70,
                sortable: false,
                align: 'center',
                formatter: function (cellvalue, options, rowObject) {
                    if (cellvalue == "启用") {
                        if (flag == false) {
                            return "<button id='openBtn' disabled class='btn btn-success btn-xs' onclick='userOpenEdit(\"" + rowObject.id + "\")'><i class='fa fa-opera button-in-i'></i>启用</button>";
                        } else {
                            return "<button id='openBtn' class='btn btn-success btn-xs' onclick='userOpenEdit(\"" + rowObject.id + "\")'><i class='fa fa-opera button-in-i'></i>启用</button>";
                        }
                    } else {
                        if (flag == false) {
                            return "<button id='resetBtn' disabled onclick='userOpenEdit(\"" + rowObject.id + "\")' class='btn btn-adn btn-xs'><i class='fa fa-adn button-in-i'></i>禁用</button>";
                        } else {
                            return "<button id='resetBtn' onclick='userOpenEdit(\"" + rowObject.id + "\")' class='btn btn-adn btn-xs'><i class='fa fa-adn button-in-i'></i>禁用</button>";
                        }
                    }
                }
            },
            {
                name: 'astate',
                index: 'astate',
                width: 70,
                align: 'center',
                sortable: false,
                formatter: function (cellvalue, options, rowObject) {
                    if (flag == false) {
                        return "<button disabled class='btn btn-group btn-xs' onclick='userPasswordReset(\"" + rowObject.id + "\")'><i class='fa fa-edit button-in-i'></i>密码重置</button>";
                    } else {
                        return "<button class='btn btn-group btn-xs' onclick='userPasswordReset(\"" + rowObject.id + "\")'><i class='fa fa-edit button-in-i'></i>密码重置</button>";
                    }
                }
            },
            {name: 'tel', index: 'tel', align: 'center', sortable: false,},
            {name: 'username', index: 'username', align: 'center', sortable: false,},
            {name: 'bankname', index: 'bankname', align: 'center', sortable: false,},
            {name: 'organizationName', index: 'organizationName', align: 'center', sortable: false,},
            {name: 'rooname', index: 'rooname', align: 'center', sortable: false,},
            {name: 'state', index: 'state', align: 'center', sortable: false,},

        ],

        viewrecords: true,
        rowNum: pageSize,
        rownumbers: false,//添加左侧行号
        rowList: [5, 10, 15],
        pager: pager_selector,
        altRows: true,
        multiselect: false,
        loadComplete: function (data) {
            var table = this;
            setTimeout(function () {
                updatePagerIcons(table);
            }, 0);
            var h = $(window).height() - ($('#grid-pager')[0].offsetHeight + 15) - ($('.result-table .box')[0].offsetTop + $('.ui-jqgrid-bdiv')[0].offsetTop + 3);
            $('.ui-jqgrid-bdiv').height(h);
        },
        autowidth: true,
        jsonReader: jsonReader,   // json中代表实际模型数据的入口
        rownumWidth: 55,
        prmNames: prmNames,
        recordtext: "显示 {0} - {1} 条 , 共 {2} 条",
        emptyrecords: "没有记录",
        loadtext: "正在加载...",
        pgtext: "第 {0} 页  ,共 {1} 页"
    });
    //初始化分页条
    showNavGrid(grid_selector, pager_selector);

    //初始化信息校验表单
    form = $("#addform").validate({
        errorElement: 'div',
        errorClass: 'help-block messages',
        focusInvalid: false,
        highlight: validateHighlight,
        success: validateSuccess,
        errorPlacement: errorPlacement
    });
    form1 = $("#Editform").validate({
        errorElement: 'div',
        errorClass: 'help-block messages',
        focusInvalid: false,
        highlight: validateHighlight,
        success: validateSuccess,
        errorPlacement: errorPlacement
    });

    //查询
    $("#queryBtn").click(function () {
        var filters = {
            'tel': $("#userAccount").val(),
            'username': $("#userName").val(),
            'rooleid': $("#sUserRole option:selected").val(),
            'bankid': $("#sUserBank option:selected").val(),
            'organization': $("#sUserOrg option:selected").val(),
            'state': $("#userState option:selected").val()

        }
        grid.jqGrid("setGridParam", {postData: filters, page: 1});
        grid.trigger('reloadGrid');
    });

    //清空
    $("#clearBtn").click(function () {
        $("#userAccount").val("");
        $("#userName").val("");
        $("#sUserRole option:first").prop("selected", 'selected');
        $("#sUserOrg option:first").prop("selected", 'selected');
        $("#sUserBank option:first").prop("selected", 'selected');
        $("#userState option:first").prop("selected", 'selected');
    })

    //加载所属银行、所属机构、使用者角色
    var selectCompany = $("#sUserBank");//银行
    var selectOrg = $("#sUserOrg");//机构
    var selectRole = $("#sUserRole");//使用者角色
    $.ajax({
        url: "getAllComOrgRole",
        type: "GET",
        dataType: "json",
        success: function (data) {
            if (data != null) {
                var org = data.allComName;//机构
                console.log("org:" + org.length);
                var company = data.allBankName;//银行
                var role = data.allRoleName;
                // console.log(company[0][0]);
                console.log("company:" + company.length);
                selectCompany.html("");
                selectOrg.html("");
                selectRole.html("");
                //向银行select传入数据
                var options = "<option value=\"0\">--请选择--</option>";
                for (var i = 0; i < company.length; i++) {
                    options += "<option value=\"" + company[i].id + "\">" + company[i].bankname + "</option>";
                }
                //向机构select传入数据
                var optionss = "<option value=\"0\">--请选择--</option>";
                for (var i = 0; i < org.length; i++) {
                    optionss += "<option value=\"" + org[i][0] + "\">" + org[i][1] + "</option>";
                }
                //向角色select传入数据
                var optionsss = "<option value=\"0\">--请选择--</option>";
                for (var i = 0; i < role.length; i++) {
                    optionsss += "<option value=\"" + role[i].id + "\">" + role[i].rooname + "</option>";
                }
                selectCompany.html(options);
                selectOrg.html(optionss);
                selectRole.html(optionsss);
            }
        }
    })
});

//重置密码
function userPasswordReset(obj) {
    bootbox.confirm("确定要重置该用户的密码？", function (result) {
        if (result) {
            $.post("resetUserPassword", {
                "id": obj,
            }, function (data) {
                if (data.resetResult == 1) {
                    alert("您的密码重置为123456，请登录后重新修改密码！");
                } else {
                    alert("密码重置失败");
                }
                grid.trigger('reloadGrid');
            });
        }
    });
}

//启用禁用的编辑
function userOpenEdit(obj) {
    bootbox.confirm("您确定要更改该用户的状态吗？", function (result) {
        if (result) {
            $.post("userOpenEdit", {
                "id": obj,
            }, function (data) {
                if (data.updateResult == 1) {
                    alert("用户状态修改成功");
                } else {
                    alert("用户状态修改失败");
                }
                grid.trigger('reloadGrid');
            });
        }
    });
}
